<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 搜索与添加区域 -->
        <el-row :gutter="20">
          <el-col :span="2">
            <el-button type="primary" @click="addDialogVisible = true">添加</el-button>
          </el-col>
          <el-col :span="8">
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              :clearable="true"
              @clear="getUserList"
            >
              <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
            </el-input>
          </el-col>
        </el-row>
      </div>

      <!-- 用户列表区域 -->
      <el-table :data="userList" :stripe="true" style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="name" label="姓名" width="180"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="role" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="{row}">
            <!-- <el-tag
              :type="row.status | statusFilter"
              :key="userStatus[row.status].label"
              effect="dark"
            >{{ userStatus[row.status].label }}</el-tag>-->
            <!-- <el-tag
              :type="userStatus[row.status].type"
              :key="userStatus[row.status].label"
              effect="dark"
            >{{ userStatus[row.status].label }}</el-tag>-->
            <el-switch v-model="row.statusV" @change="userStatusChange(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170">
          <template slot-scope="{row}">
            <!-- 查看 -->
            <el-button type="info" icon="el-icon-view" circle size="mini"></el-button>
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              size="mini"
              @click="showEditDialog(row.id)"
            ></el-button>
            <!-- 分配权限 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                circle
                size="mini"
                @click="updateUserRolesView(row)"
              ></el-button>
            </el-tooltip>

            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="mini"
              @click="deleteUserById(row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="pageSizes"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户 Dialog -->
    <el-dialog title="添加" :visible.sync="addDialogVisible" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <!-- <span>需要注意的是内容是默认不居中的</span> -->

      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" required>
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="密码确认" prop="passwordCheck" required>
          <el-input v-model="addForm.passwordCheck"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" required>
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone" required>
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetAddForm">重 置</el-button>
        <el-button type="primary" @click="addFormPost">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="80px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="editForm.name" readonly disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" required>
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone" required>
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFormPost">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="角色分配" :visible.sync="roleDialogFormVisible">
      <div>
        <p>当前的用户： {{userInfo.name}}</p>
        <p>当前的角色：{{userInfo.role}}</p>
        <p>
          修改角色为：
          <el-select v-model="selectedRoleId" filterable placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUserRoles()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'info',
        1: ''
      }
      return statusMap[status]
    }
  },
  data() {
    var validateUsername = (rule, value, callback) => {
      var patt = /^[_,A-z,0-9]{3,10}$/i
      if (!patt.test(value)) {
        callback(new Error('用户名必须是字母下划线或数字'))
      }
      callback()
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var checkPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号去哪了'))
      }

      var patt = /^1\d{10}$/
      if (!patt.test(value)) {
        callback(new Error('手机号好像是11位的数字'))
      }
      callback()
    }
    return {
      // 获取用户列表的参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 分頁組件
      pageSizes: [10, 15, 20],
      // 用戶列表
      userList: [],
      // 记录总条数
      total: 0,
      // 用户状态
      userStatus: [
        { type: 'info', label: '禁用', status: false },
        { type: '', label: '启用', status: true }
      ],
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        name: '',
        password: '',
        passwordCheck: '',
        email: '',
        phone: ''
      },
      // 添加用户的表单验证规则对象
      addFormRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3-10 个字符', trigger: 'blur' },
          { validator: validateUsername, trigger: 'blur' }
        ],
        password: [{ min: 6, message: '长度最少6位', trigger: 'blur' }],
        passwordCheck: [{ validator: validatePass2, trigger: 'blur' }],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phone: [{ validator: checkPhone, trigger: 'blur' }]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的哟过户信息对象
      editForm: {},
      // 修改用户的表单验证规则对象
      editFormRules: {
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phone: [{ validator: checkPhone, trigger: 'blur' }]
      },
      // 控制角色非配对话框显示与隐藏
      roleDialogFormVisible: false,
      // 要操作的用户信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      // 被选中的用户角色
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      await this.$http
        .get('users', { params: this.queryInfo })
        .then(res => {
          // console.log(res)
          res = res.data
          if (!res.code || res.code == 0)
            return this.$message.error(res.msg || '获取数据失败')
          this.userList = res.data.users.map(v => {
            this.$set(v, 'statusV', v.status == 1 ? true : false)
            return v
          })
          this.total = res.data.total
        })
        .catch(err => {
          return this.$message.error(err.message)
        })
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 监听用户状态改变
    async userStatusChange(row) {
      // console.log(row)
      await this.$http
        .put(`/users/${row.id}/status/${row.status}`)
        .then(res => {
          res = res.data
          if (res.code || res.code == 0) {
            // row.statusV = res.data.status == 1 ? true : false
            row.statusV = !row.statusV
            return this.$message.error(res.msg || '修改用户失败')
          }
          return this.$message.success(res.msg || '修改用户成功')
        })
        .catch(err => {
          return this.$message.error(err.message)
        })
    },
    // 监听添加用户对话框 关闭 dialog
    addDialogClosed() {
      this.resetAddForm()
    },
    // 重置新建表单
    resetAddForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 新增用户添加
    addFormPost() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        await this.$http
          .post('users', this.addForm)
          .then(res => {
            // console.log(res)
            res = res.data
            if (!res.code || res.code == 0)
              return this.$message.error(res.msg || '添加失败')

            this.$message.success('添加成功')
            this.resetAddForm()
            this.addDialogVisible = false
            this.getUserList()
          })
          .catch(err => {
            return this.$message.error(err.message)
          })
      })
    },
    // 显示编辑用户的对话框
    async showEditDialog(id) {
      // 我个人不推荐这样结构化赋值
      const { data: res } = await this.$http.get(`users/${id}`).catch(err => {
        return this.$message.error(err.message)
      })

      if (undefined == res) return this.$message.error('网络错误')

      if (!res.code || res.code == 0)
        return this.$message.error(res.msg || '获取用户信息失败')

      this.editForm = res.data

      this.editDialogVisible = true
    },
    // 提交修改
    async editFormPost() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        this.$http
          .put(`users/${this.editForm.id}`, {
            email: this.editForm.email,
            phone: this.editForm.phone
          })
          .then(res => {
            res = res.data
            if (!res.code || res.code == 0)
              return this.$message.error(res.msg || '修改失败')

            this.$message.success('修改成功')
            this.editDialogVisible = false
            this.getUserList()
          })
          .catch(err => {
            return this.$message.error(err.message)
          })
      })
    },
    // 根据id删除操作
    async deleteUserById(id) {
      // 弹窗询问是否删除
      await this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http
            .delete(`users/${id}`)
            .then(res => {
              res = res.data
              if (!res.code || res.code == 0)
                return this.$message.error(res.msg || '删除失败')

              this.$message.success(res.msg || '删除成功')
              this.getUserList()
            })
            .catch(err => {
              return this.$message.error(err.message)
            })
        })
        .catch(() => {
          // 可以这样使用
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 打开修改角色面板
    async updateUserRolesView(userInfo) {
      this.userInfo = userInfo

      // 获取所有角色列表
      await this.$http
        .get('/roles')
        .then(res => {
          res = res.data
          // console.log(res)

          if (!res.code || res.code == 0)
            return this.$message.error(res.msg || '操作失败')

          this.rolesList = res.data

          this.roleDialogFormVisible = true
        })
        .catch(err => {
          return this.$message.error(err.message)
        })
    },
    // 角色修改操作
    async updateUserRoles() {
      if (!this.selectedRoleId)
        return this.$message.error('未知的角色信息')

      await this.$http
        .put(`users/${this.userInfo.id}/roleId/${this.selectedRoleId}`)
        .then(res => {
          res = res.data

          if (!res.code || res.code == 0)
            return this.$message.error(res.msg || '操作失败')

          this.getUserList()
          this.roleDialogFormVisible = false
          this.selectedRoleId = ''
          return this.$message.success(res.msg || '操作成功')
          
        })
        .catch(err => {
          return this.$message.error(err.message)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>